package com.itheima.stock.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author by itheima
 * @Date 2022/6/1
 * @Description 定义redis缓存的配置类
 */
@Configuration
public class RedisCacheConfig {

        /**
         * 配置redisTemplate bean，自定义数据的序列化的方式
         * @param connectionFactory 连接redis的工厂，底层有场景依赖启动时，自动加载
         * @return
         */
        @Bean
        public RedisTemplate<Object, Object> redisTemplate(@Autowired RedisConnectionFactory connectionFactory) {
                RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
                //默认的Key序列化器为：JdkSerializationRedisSerializer
                redisTemplate.setKeySerializer(stringRedisSerializer());
                redisTemplate.setHashKeySerializer(stringRedisSerializer());
                //指定value的序列化方式
                redisTemplate.setValueSerializer(stringRedisSerializer());
                redisTemplate.setHashValueSerializer(stringRedisSerializer());
                redisTemplate.setConnectionFactory(connectionFactory);
                //刷新配置,如果不指定序列化的方式，则默认使用jdk序列化的方式：JdkSerializationRedisSerializer
                redisTemplate.afterPropertiesSet();
                return redisTemplate;
        }

        /**
         * 定义序列化方式
         * @return
         */
        @Bean
        public StringRedisSerializer stringRedisSerializer(){
                return new StringRedisSerializer();
        }


}
